#!/bin/sh

mkdir -p "/run/user/"$(id -u)""
xidfile="/run/user/"$(id -u)"/glinks-tabbed.xid"
useragent="Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:74.0) Gecko/20100101 Firefox/74.0"

if [ ! $(pgrep -x miniwebproxy) ]; then
cd ~/git/miniwebproxy/
./miniwebproxy &
echo 'turning on web proxy'
fi

[ "$#" -gt 0 ] && uri="$1"

runtabbed() {
	echo spawning
	tabbed -cdn "Links" -r 3 links -g -w '' \
	-https-proxy localhost:8090 -http-proxy localhost:8090 -http.fake-user-agent "$useragent" "$uri" > $xidfile 2>/dev/null &
}

if [ ! -r "$xidfile" ];
then
	runtabbed
else
	xid=$(cat "$xidfile")
	xprop -id "$xid" >/dev/null 2>&1
	if [ $? -gt 0 ];
	then
		runtabbed
	else
		links -g -w "$xid" -https-proxy localhost:8090 -http-proxy localhost:8090 -http.fake-user-agent "$useragent" "$uri" &
	fi
fi
